package com.ocom.payconfig.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.entity.card.*;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.entity.human.EntityDeptInfo;
import com.ocom.common.entity.master.EntityPayChannel;
import com.ocom.common.entity.payconfig.EntityReceiptAddress;
import com.ocom.common.enums.OpTypeDiffEnum;
import com.ocom.common.enums.OpTypeEnum;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.ConsumeDetailErrorRequest;
import com.ocom.common.request.payconfig.TotalTurnoverRequest;
import com.ocom.common.request.payconfig.adreceiptinfo.GetAdReceiptInfoRequest;
import com.ocom.common.request.web.*;
import com.ocom.common.request.xfrecde.DeptReportVo;
import com.ocom.common.request.xfrecde.GetGroupDataRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.xfrecode.ChannelDataVo;
import com.ocom.payconfig.client.XfRecordFeign;
import com.ocom.payconfig.service.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class XFPayController {

  @Autowired
  private XfMealInfoService mealInfoService;

  @Autowired
  private XfRecordFeign xfRecordFeign;

  @Autowired
  CompanyInfoService companyInfoService;

  @Autowired
  private XfMerchantInfoService merchantInfoService;

  @Autowired
  private ConsTypeConfigService consTypeConfigService;

  @Autowired
  private XfMerchPayInfoService xfMerchPayInfoService;

  @Autowired
  private PayChannelService payChannelService;

  @Autowired
  private XfRecordProcessService xfRecordProcessService;

  @Autowired
  private MealOrderController mealOrderController;

  @Autowired
  private ReceiptAddressService receiptAddressService;


  @PostMapping(PayConfigUrl.Url_getTurnoverReports)
  public Result getTurnoverReports(@RequestBody TotalTurnoverRequest totalTurnoverRequest) {

    //查询月报表：
    if (totalTurnoverRequest.getSummaryDate().equals("")) {
      totalTurnoverRequest.setSummaryDate(DateUtils.getStrDate(new Date(), DateUtils.YYYY_MM));
    }
        /* 1.当summaryDate=“yyyy-MM”时，查询出月明细列表 detailList。
        (1)当 reportType=0 时，查询每天各餐段汇总结果；
        (2)当 reportType=1 时，查询每天各支付方式汇总结果；
        (3)当 reportType=2 时，查询每天各收款账户汇总结果；*/

    Result result = null;
    String dateGe = "";
    if (totalTurnoverRequest.getSummaryDate().length() == 4) {
      if (totalTurnoverRequest.getReportType() == 0) {
        result = xfRecordFeign.monthTotalMealNo(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
      } else if (totalTurnoverRequest.getReportType() == 1) {
        result = xfRecordFeign.monthTotalPayType(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
      } else {
        result = xfRecordFeign.monthTotalAccount(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
      }
      dateGe = "yyyy-MM";
    } else {
      if (totalTurnoverRequest.getReportType() == 0) {
        result = xfRecordFeign.times(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
      } else if (totalTurnoverRequest.getReportType() == 1) {
        result = xfRecordFeign.dayTotalPayType(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
      } else {
        result = xfRecordFeign.dayTotalAccount(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
      }
      dateGe = "yyyy-MM-dd";
    }

    int orderNum = 0;
    int amount = 0;
    if (result.getCode() == 200) {
      if (result.getData() == null) {

      }
      JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(result.getData()));

      JSONArray dateListArray = new JSONArray();
      JSONObject jsonObject = new JSONObject();

      for (Object o : jsonArray) {
        JSONObject reJsonObject = JSON.parseObject(JSON.toJSONString(o));
        String key = reJsonObject.getString("stime");
        reJsonObject.put("amount", -reJsonObject.getInteger("amount"));
        reJsonObject.put("refundAmount", -reJsonObject.getInteger("refundAmount"));
        JSONArray reJsonArray = null;
        if (jsonObject.get(key + "_detailList") == null) {
          reJsonArray = new JSONArray();
        } else {
          reJsonArray = JSON.parseArray(JSON.toJSONString(jsonObject.get(key + "_detailList")));
        }
        if (totalTurnoverRequest.getReportType() == 0) {
          if(reJsonObject.getString("reportType").equals("-1")){
            reJsonObject.put("detail", "商店");
          }else if(reJsonObject.getString("reportType").equals("0")){
            reJsonObject.put("detail", "其他餐段");
          }else{
            List<EntityXfMealInfo> entityXfMealInfos = mealInfoService.GetMealNameInfo(null, totalTurnoverRequest.getCompanyID(), reJsonObject.getString("reportType"), null);
            for (EntityXfMealInfo entityXfMealInfo : entityXfMealInfos) {
              if (entityXfMealInfo.getMealNo().equals(reJsonObject.getString("reportType"))) {
                reJsonObject.put("detail", entityXfMealInfo.getMealName());
              }
            }
          }
        } else if (totalTurnoverRequest.getReportType() == 1) {
          reJsonObject.put("detail", OpTypeEnum.getName(reJsonObject.getInteger("reportType")));
        } else {
          reJsonObject.put("chargeNum", reJsonObject.getInteger("chargeNum"));
          reJsonObject.put("chargeAmount", reJsonObject.getInteger("chargeAmount"));
          reJsonObject.put("detail", OpTypeDiffEnum.getName(reJsonObject.getInteger("reportType")));
        }
        reJsonArray.add(reJsonObject);

        if (StringUtils.isEmpty(jsonObject.getString(key))) {
          jsonObject.put(key, reJsonObject.getString("stime"));
          jsonObject.put(key + "_orderNum", reJsonObject.getInteger("orderNum"));
          jsonObject.put(key + "_amount", reJsonObject.getInteger("amount"));
          dateListArray.add(key);
        } else {
          jsonObject.put(key, reJsonObject.getString("stime"));
          jsonObject.put(key + "_orderNum", jsonObject.getInteger(key + "_orderNum") + reJsonObject.getInteger("orderNum"));
          jsonObject.put(key + "_amount", jsonObject.getInteger(key + "_amount") + reJsonObject.getInteger("amount"));
        }
        orderNum = orderNum + reJsonObject.getInteger("orderNum");
        amount = amount + reJsonObject.getInteger("amount");
        jsonObject.put(key + "_detailList", reJsonArray);
      }

      if (totalTurnoverRequest.getReportType() == 0) {
        Result results = null;
        if (totalTurnoverRequest.getSummaryDate().length() == 4) {
          results = xfRecordFeign.monthMealNoCanteenNo(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
        } else {
  //        results = xfRecordFeign.dayTotalMealNoCanteenNo(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
          results = ResultUtil.error(ResultEnum.Err_1);
        }
        if (results.getCode() == 200) {
          JSONArray jsonArrays = JSON.parseArray(JSON.toJSONString(results.getData()));
          for (Object array : jsonArrays) {
            JSONObject reJsonObjects = JSON.parseObject(JSON.toJSONString(array));
            String key = reJsonObjects.getString("stime");

            JSONArray reJsonArray = null;
            if (jsonObject.get(key + "_detailList") == null) {
              reJsonArray = new JSONArray();
            } else {
              reJsonArray = JSON.parseArray(JSON.toJSONString(jsonObject.get(key + "_detailList")));
            }

            reJsonObjects.put("amount", -reJsonObjects.getInteger("amount"));
            reJsonObjects.put("refundAmount", -reJsonObjects.getInteger("refundAmount"));
            EntityConsTypeConfig entityConsTypeConfig = consTypeConfigService.selectXFConsTypeName(totalTurnoverRequest.getCompanyID(), reJsonObjects.getInteger("reportType"));
            if (entityConsTypeConfig == null) {
              reJsonObjects.put("detail", "消费类型," + reJsonObjects.getInteger("reportType"));
            } else {
              reJsonObjects.put("detail", entityConsTypeConfig.getConsName());
            }
            if (StringUtils.isEmpty(jsonObject.getString(key))) {
              jsonObject.put(key, reJsonObjects.getString("stime"));
              jsonObject.put(key + "_orderNum", reJsonObjects.getInteger("orderNum"));
              jsonObject.put(key + "_amount", reJsonObjects.getInteger("amount"));
              dateListArray.add(key);
            } else {
              jsonObject.put(key, reJsonObjects.getString("stime"));
              jsonObject.put(key + "_orderNum", jsonObject.getInteger(key + "_orderNum") + reJsonObjects.getInteger("orderNum"));
              jsonObject.put(key + "_amount", jsonObject.getInteger(key + "_amount") + reJsonObjects.getInteger("amount"));
            }
            reJsonArray.add(reJsonObjects);
            jsonObject.put(key + "_detailList", reJsonArray);
            orderNum = orderNum + reJsonObjects.getInteger("orderNum");
            amount = amount + reJsonObjects.getInteger("amount");
          }
        }
      }

      boolean buquan =false;
      List<EntityXfMealInfo> entityXfMealInfos = mealInfoService.GetMealNameInfo(null, totalTurnoverRequest.getCompanyID(), null, null);


      JSONArray dateLisArray = new JSONArray();
      for (Object o : dateListArray) {
        JSONObject dateLisObject = new JSONObject();
        String reKey = String.valueOf(o);
        dateLisObject.put("strDate", reKey);
        dateLisObject.put("date", dateGe);
        dateLisObject.put("orderNum", jsonObject.getInteger(reKey + "_orderNum"));
        dateLisObject.put("amount", jsonObject.getInteger(reKey + "_amount"));
        dateLisObject.put("detailList", jsonObject.get(reKey + "_detailList"));
        if(!buquan && totalTurnoverRequest.getReportType()==0){
          Object oj = jsonObject.get(reKey + "_detailList");

          List<INVOKE> invoList =JSON.parseArray(JSON.toJSONString(oj), INVOKE.class);

          List<String>  meals = invoList.stream().map(INVOKE::getReportType).collect(Collectors.toList());

          List<INVOKE> invoList2 =new ArrayList<>();

          for (EntityXfMealInfo entityXfMealInfo:entityXfMealInfos){
            if(!meals.contains(entityXfMealInfo.getMealNo())){
              INVOKE invo = new INVOKE();
              invo.setAmount(0);
              invo.setOrderNum(0);
              invo.setRefundNum(0);
              invo.setRefundAmount(0);
              invo.setDetail(entityXfMealInfo.getMealName());
              invo.setReportType(entityXfMealInfo.getMealNo());
              invo.setStime(reKey);
              invoList2.add(invo);
            }else{
              for (INVOKE invoke:invoList){
                if(invoke.getReportType().equals(entityXfMealInfo.getMealNo())){
                  invoList2.add(invoke);
                  break;
                }
              }
            }
          }
          for (INVOKE invoke:invoList){
            if(invoke.getReportType().equals("0") || invoke.getReportType().equals("-1")  ){
              invoList2.add(invoke);
              break;
            }
          }
          dateLisObject.put("detailList", invoList2);
          buquan =true;
        }
        dateLisArray.add(dateLisObject);
      }
      Map<String, Object> map = new HashMap<>();
      Map<String, Object> pageFormatMap = new HashMap<>();
      pageFormatMap.put("pageTitle", "营业额统计");
      map.put("pageFormat", pageFormatMap);
      EntityXfMerchantInfo entityXfMerchantInfo = merchantInfoService.GetMerchInfo(totalTurnoverRequest.getCompanyID(), totalTurnoverRequest.getMerchID());
      EntityCompanyInfo entityCompanyInfo = companyInfoService.GetCompanyInfo(totalTurnoverRequest.getCompanyID());
      if (entityXfMerchantInfo == null || totalTurnoverRequest.getMerchID() == -1) {
        map.put("merchName", entityCompanyInfo.getComName());
      } else {
        map.put("merchName", entityXfMerchantInfo.getMerchName());
      }
      map.put("reportType", totalTurnoverRequest.getReportType());
      map.put("summaryDate", totalTurnoverRequest.getSummaryDate());
      map.put("orderNum", orderNum);
      map.put("amount", amount);
      map.put("dateList", dateLisArray);
      map.put("createDate", DateUtils.getStrDate(entityCompanyInfo.getCreateTime(), DateUtils.YYYY_MM));
      return ResultUtil.success(map);
    } else {
      return result;
    }
  }


  @PostMapping(PayConfigUrl.Url_getTurnoverReportsXM)
  public Result getTurnoverReportsXM(@RequestBody TotalTurnoverRequest totalTurnoverRequest) {

    //查询月报表：
    if (totalTurnoverRequest.getSummaryDate().equals("")) {
      totalTurnoverRequest.setSummaryDate(DateUtils.getStrDate(new Date(), DateUtils.YYYY_MM));
    }
    /** 1.当summaryDate=“yyyy-MM”时，查询出月明细列表 detailList。
     (1)当 reportType=0 时，查询每天各餐段汇总结果；
     (2)当 reportType=1 时，查询每天各支付方式汇总结果；
     (3)当 reportType=2 时，查询每天各收款账户汇总结果；*/

    Result result = null;
    String dateGe = "";
    if (totalTurnoverRequest.getSummaryDate().length() == 4) {
      if (totalTurnoverRequest.getReportType() == 0) {
        result = xfRecordFeign.monthTotalMealNo(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
      } else if (totalTurnoverRequest.getReportType() == 1) {
        result = xfRecordFeign.monthTotalPayType(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
      } else {
        result = xfRecordFeign.monthTotalAccount(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
      }
      dateGe = "yyyy-MM";
    } else {
      if (totalTurnoverRequest.getReportType() == 0) {
        //result = xfRecordFeign.times(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
        result = xfRecordFeign.timesXM(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
      } else if (totalTurnoverRequest.getReportType() == 1) {
        result = xfRecordFeign.dayTotalPayTypeXM(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
      } else {
        result = xfRecordFeign.dayTotalAccountXM(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
      }
      dateGe = "yyyy-MM-dd";
    }

    int orderNum = 0;
    int amount = 0;
    if (result.getCode() == 200) {
      if (result.getData() == null) {

      }
      JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(result.getData()));

      JSONArray dateListArray = new JSONArray();
      JSONObject jsonObject = new JSONObject();

      for (Object o : jsonArray) {
        JSONObject reJsonObject = JSON.parseObject(JSON.toJSONString(o));
        String key = reJsonObject.getString("stime");
        reJsonObject.put("amount", -reJsonObject.getInteger("amount"));
        reJsonObject.put("refundAmount", -reJsonObject.getInteger("refundAmount"));
        JSONArray reJsonArray = null;
        if (jsonObject.get(key + "_detailList") == null) {
          reJsonArray = new JSONArray();
        } else {
          reJsonArray = JSON.parseArray(JSON.toJSONString(jsonObject.get(key + "_detailList")));
        }
        if (totalTurnoverRequest.getReportType() == 0) {
          boolean xfMealInfo = true;
          List<EntityXfMealInfo> entityXfMealInfos = mealInfoService.GetMealNameInfo(null, totalTurnoverRequest.getCompanyID(), reJsonObject.getString("reportType"), null);
          for (EntityXfMealInfo entityXfMealInfo : entityXfMealInfos) {
            if (entityXfMealInfo.getMealNo().equals(reJsonObject.getString("reportType"))) {
              xfMealInfo = false;
              reJsonObject.put("detail", entityXfMealInfo.getMealName());
            }
          }
          if (xfMealInfo) {
            reJsonObject.put("detail", "其他餐段");
          }
        } else if (totalTurnoverRequest.getReportType() == 1) {
          reJsonObject.put("detail", OpTypeEnum.getName(reJsonObject.getInteger("reportType")));
        } else {
          reJsonObject.put("chargeNum", reJsonObject.getInteger("chargeNum"));
          reJsonObject.put("chargeAmount", reJsonObject.getInteger("chargeAmount"));
          reJsonObject.put("detail", OpTypeDiffEnum.getName(reJsonObject.getInteger("reportType")));
        }
        reJsonArray.add(reJsonObject);

        if (StringUtils.isEmpty(jsonObject.getString(key))) {
          jsonObject.put(key, reJsonObject.getString("stime"));
          jsonObject.put(key + "_orderNum", reJsonObject.getInteger("orderNum"));
          jsonObject.put(key + "_amount", reJsonObject.getInteger("amount"));
          dateListArray.add(key);
        } else {
          jsonObject.put(key, reJsonObject.getString("stime"));
          jsonObject.put(key + "_orderNum", jsonObject.getInteger(key + "_orderNum") + reJsonObject.getInteger("orderNum"));
          jsonObject.put(key + "_amount", jsonObject.getInteger(key + "_amount") + reJsonObject.getInteger("amount"));
        }
        orderNum = orderNum + reJsonObject.getInteger("orderNum");
        amount = amount + reJsonObject.getInteger("amount");
        jsonObject.put(key + "_detailList", reJsonArray);
      }

      if (totalTurnoverRequest.getReportType() == 0) {
        Result results = null;
//        if (totalTurnoverRequest.getSummaryDate().length() == 4) {
//          results = xfRecordFeign.monthMealNoCanteenNo(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
//        } else {
//          results = xfRecordFeign.dayTotalMealNoCanteenNo(JSON.parseObject(JSON.toJSONString(totalTurnoverRequest)));
//        }
//        if (results.getCode() == 200) {
//          JSONArray jsonArrays = JSON.parseArray(JSON.toJSONString(results.getData()));
//          for (Object array : jsonArrays) {
//            JSONObject reJsonObjects = JSON.parseObject(JSON.toJSONString(array));
//            String key = reJsonObjects.getString("stime");
//
//            JSONArray reJsonArray = null;
//            if (jsonObject.get(key + "_detailList") == null) {
//              reJsonArray = new JSONArray();
//            } else {
//              reJsonArray = JSON.parseArray(JSON.toJSONString(jsonObject.get(key + "_detailList")));
//            }
//
//            reJsonObjects.put("amount", -reJsonObjects.getInteger("amount"));
//            reJsonObjects.put("refundAmount", -reJsonObjects.getInteger("refundAmount"));
//            EntityConsTypeConfig entityConsTypeConfig = consTypeConfigService.selectXFConsTypeName(totalTurnoverRequest.getCompanyID(), reJsonObjects.getInteger("reportType"));
//            if (entityConsTypeConfig == null) {
//              reJsonObjects.put("detail", "消费类型," + reJsonObjects.getInteger("reportType"));
//            } else {
//              reJsonObjects.put("detail", entityConsTypeConfig.getConsName());
//            }
//            if (StringUtils.isEmpty(jsonObject.getString(key))) {
//              jsonObject.put(key, reJsonObjects.getString("stime"));
//              jsonObject.put(key + "_orderNum", reJsonObjects.getInteger("orderNum"));
//              jsonObject.put(key + "_amount", reJsonObjects.getInteger("amount"));
//              dateListArray.add(key);
//            } else {
//              jsonObject.put(key, reJsonObjects.getString("stime"));
//              jsonObject.put(key + "_orderNum", jsonObject.getInteger(key + "_orderNum") + reJsonObjects.getInteger("orderNum"));
//              jsonObject.put(key + "_amount", jsonObject.getInteger(key + "_amount") + reJsonObjects.getInteger("amount"));
//            }
//            reJsonArray.add(reJsonObjects);
//            jsonObject.put(key + "_detailList", reJsonArray);
//            orderNum = orderNum + reJsonObjects.getInteger("orderNum");
//            amount = amount + reJsonObjects.getInteger("amount");
//          }
//        }
      }

      JSONArray dateLisArray = new JSONArray();


      boolean buquan =false ;



      List<EntityXfMealInfo> entityXfMealInfos = mealInfoService.GetMealNameInfo(null, totalTurnoverRequest.getCompanyID(), null, null);


      for (Object o : dateListArray) {
        JSONObject dateLisObject = new JSONObject();
        String reKey = String.valueOf(o);
        dateLisObject.put("strDate", reKey);
        dateLisObject.put("date", dateGe);
        dateLisObject.put("orderNum", jsonObject.getInteger(reKey + "_orderNum"));
        dateLisObject.put("amount", jsonObject.getInteger(reKey + "_amount"));
        dateLisObject.put("detailList", jsonObject.get(reKey + "_detailList"));
        if(!buquan && totalTurnoverRequest.getReportType()==0){
          Object oj = jsonObject.get(reKey + "_detailList");

          List<INVOKE> invoList =JSON.parseArray(JSON.toJSONString(oj), INVOKE.class);

          List<String>  meals = invoList.stream().map(INVOKE::getReportType).collect(Collectors.toList());

          List<INVOKE> invoList2 =new ArrayList<>();

          for (EntityXfMealInfo entityXfMealInfo:entityXfMealInfos){
            if(!meals.contains(entityXfMealInfo.getMealNo())){
              INVOKE invo = new INVOKE();
              invo.setAmount(0);
              invo.setOrderNum(0);
              invo.setRefundNum(0);
              invo.setRefundAmount(0);
              invo.setDetail(entityXfMealInfo.getMealName());
              invo.setReportType(entityXfMealInfo.getMealNo());
              invo.setStime(reKey);
              invoList2.add(invo);
            }else{
              for (INVOKE invoke:invoList){
                if(invoke.getReportType().equals(entityXfMealInfo.getMealNo())){
                  invoList2.add(invoke);
                  break;
                }
              }
            }
          }
          dateLisObject.put("detailList", invoList2);
          buquan =true;
        }


        dateLisArray.add(dateLisObject);
      }
      Map<String, Object> map = new HashMap<>();
      Map<String, Object> pageFormatMap = new HashMap<>();
      pageFormatMap.put("pageTitle", "营业额统计");
      map.put("pageFormat", pageFormatMap);
      EntityXfMerchantInfo entityXfMerchantInfo = merchantInfoService.GetMerchInfo(totalTurnoverRequest.getCompanyID(), totalTurnoverRequest.getMerchID());
      EntityCompanyInfo entityCompanyInfo = companyInfoService.GetCompanyInfo(totalTurnoverRequest.getCompanyID());
      if (entityXfMerchantInfo == null || totalTurnoverRequest.getMerchID() == -1) {
        map.put("merchName", entityCompanyInfo.getComName());
      } else {
        map.put("merchName", entityXfMerchantInfo.getMerchName());
      }
      map.put("reportType", totalTurnoverRequest.getReportType());
      map.put("summaryDate", totalTurnoverRequest.getSummaryDate());
      map.put("orderNum", orderNum);
      map.put("amount", amount);
      map.put("dateList", dateLisArray);
      map.put("createDate", DateUtils.getStrDate(entityCompanyInfo.getCreateTime(), DateUtils.YYYY_MM));
      return ResultUtil.success(map);
    } else {
      return result;
    }
  }

  @Data
  private static class INVOKE {
    Integer amount=0;
    String detail;
    Integer orderNum=0;
    Integer refundAmount=0;
    Integer refundNum=0;
    String reportType;
    String stime;
  }


  /**
   * @param getConsDeptReportsRequest
   * @return com.ocom.common.resp.Result
   * @Description:获取部门消费汇总报表（getConsDeptList）
   * @author lu
   * @date 2023/2/22 10:04
   */
  @PostMapping(PayConfigUrl.Url_getConsDeptList)
  public Result getConsDeptList(@Validated @RequestBody GetConsDeptReportsRequest getConsDeptReportsRequest) throws CloneNotSupportedException {

    //调用接口3.0微服务-部门人事接口department/getDeptList，获取部门下所有子部门集合@deptList；
    List<EntityDeptInfo> entityDeptInfos = JSON.parseArray(getConsDeptReportsRequest.getDeptIds(), EntityDeptInfo.class);
    String deptIds = "";
    Long grade = 99l;
    for (int i = 0; i < entityDeptInfos.size(); i++) {
      if (i == 0) {
        deptIds = String.valueOf(entityDeptInfos.get(i).getDeptId());
      } else {
        deptIds = deptIds + "," + entityDeptInfos.get(i).getDeptId();
      }
      if (entityDeptInfos.get(i).getGrade() < grade) {
        grade = entityDeptInfos.get(i).getGrade();
      }
    }
    getConsDeptReportsRequest.setDeptIds(deptIds);
    //调用接口3.0微服务-消费配置 getConsDeptReports，获取各部门汇总结果集@consDeptRep
    Result result = xfRecordFeign.getConsDeptReports(getConsDeptReportsRequest);
    if (result.getCode() != 200) {
      return result;
    }
    JSONObject dataJsonObject = JSON.parseObject(JSON.toJSONString(result.getData()), JSONObject.class);
    List<DeptReportVo> objectList = JSON.parseArray(JSON.toJSONString(dataJsonObject.get("list")), DeptReportVo.class);

    List<Long> deptIdList = new ArrayList<>();
    if (objectList != null && objectList.size() > 0) {
      deptIdList = objectList.stream().map(DeptReportVo -> DeptReportVo.getDeptId()).collect(Collectors.toList());
    }

    List<EntityXfMealInfo> entityXfMealInfos = mealInfoService.GetMealNameInfo(null, getConsDeptReportsRequest.getComId(), null, null);
    EntityXfMealInfo entityXfMealInfo3=new EntityXfMealInfo();
    entityXfMealInfo3.setMealNo("0");
    entityXfMealInfo3.setMealName("餐段外");
    entityXfMealInfos.add(entityXfMealInfo3);

    List<DeptReportVo> reList = new ArrayList<>();

    for (EntityDeptInfo entityDeptInfo : entityDeptInfos) {
      DeptReportVo deptReportVo=new DeptReportVo();
      deptReportVo.setGrade(entityDeptInfo.getGrade());
      deptReportVo.setParentDeptID(entityDeptInfo.getParentDeptId());
      deptReportVo.setDeptId(entityDeptInfo.getDeptId());
      deptReportVo.setDeptName(entityDeptInfo.getDeptName());
      deptReportVo.setMealNo("");

      DeptReportVo deptReportVo2=new DeptReportVo();
      deptReportVo2.setGrade(entityDeptInfo.getGrade()+1);
      deptReportVo2.setParentDeptID(entityDeptInfo.getDeptId());
      deptReportVo2.setDeptId(entityDeptInfo.getDeptId()+900000l);
      deptReportVo2.setDeptName(entityDeptInfo.getDeptName()+"(直属)");
      deptReportVo2.setMealNo("");

      List<EntityDeptInfo> list2 = new ArrayList<>();
      List<Long> ins = new ArrayList<>();
      ins.add(entityDeptInfo.getDeptId());
      List<EntityDeptInfo> deptInfoList = loop(entityDeptInfos, list2, ins);

      List<Long> childDeptIds = deptInfoList.stream().map(EntityDeptInfo -> EntityDeptInfo.getDeptId()).collect(Collectors.toList());

      if (deptInfoList.size() > 1) {

        //有数据
        for (EntityXfMealInfo entityXfMealInfo:entityXfMealInfos){
          DeptReportVo.DeptMealVO deptMealVO =new DeptReportVo.DeptMealVO();
          deptMealVO.setMealNo(entityXfMealInfo.getMealNo());
          deptMealVO.setMealName(entityXfMealInfo.getMealName());

          for (DeptReportVo deptReportVo1:objectList){
            if (!childDeptIds.contains(deptReportVo1.getDeptId())
                    || !deptReportVo1.getMealNo().equals(entityXfMealInfo.getMealNo())) continue;
            if(deptReportVo1.getMealNo().equals(entityXfMealInfo.getMealNo())){
              deptMealVO.addToAmount(deptReportVo1.getAllAmount());
              deptMealVO.addToDiscount(deptReportVo1.getAllDiscount());
              deptMealVO.addToRealAmount(deptReportVo1.getAllRealAmount());
              deptMealVO.addToTimes(deptReportVo1.getAllTimes());
            }
            deptReportVo.setSTime(deptReportVo1.getSTime());
            deptReportVo.addToAllAmount(deptReportVo1.getAllAmount());
            deptReportVo.addToAllDiscount(deptReportVo1.getAllDiscount());
            deptReportVo.addToAllRealAmount(deptReportVo1.getAllRealAmount());
            deptReportVo.addToAllTimes(deptReportVo1.getAllTimes());
            deptReportVo.addToDkAmount(deptReportVo1.getDkAmount());
            deptReportVo.addToDkTimes(deptReportVo1.getDkTimes());
            deptReportVo.addToXjAmount(deptReportVo1.getXjAmount());
            deptReportVo.addToBtAmount(deptReportVo1.getBtAmount());
            deptReportVo.addToYhqAmount(deptReportVo1.getYhqAmount());
            deptReportVo.addToXnzhTimes(deptReportVo1.getXnzhTimes());
            deptReportVo.addToJcAmount(deptReportVo1.getJcAmount());
            deptReportVo.addToJcTimes(deptReportVo1.getJcTimes());
          }

          deptReportVo.getDeptMealVOList().add(deptMealVO);
        }
        reList.add(deptReportVo);

        //有数据
        for (EntityXfMealInfo entityXfMealInfo:entityXfMealInfos){
          DeptReportVo.DeptMealVO deptMealVO =new DeptReportVo.DeptMealVO();
          deptMealVO.setMealNo(entityXfMealInfo.getMealNo());
          deptMealVO.setMealName(entityXfMealInfo.getMealName());
          if(deptIdList.contains(entityDeptInfo.getDeptId())){
            for (DeptReportVo deptReportVo1:objectList){
              if (!deptReportVo1.getDeptId().equals(entityDeptInfo.getDeptId())
                      || !deptReportVo1.getMealNo().equals(entityXfMealInfo.getMealNo())) continue;
              if(deptReportVo1.getMealNo().equals(entityXfMealInfo.getMealNo())){
                deptMealVO.setAmount(deptReportVo1.getAllAmount());
                deptMealVO.setDiscount(deptReportVo1.getAllDiscount());
                deptMealVO.setRealAmount(deptReportVo1.getAllRealAmount());
                deptMealVO.setTimes(deptReportVo1.getAllTimes());
              }
              deptReportVo2.setSTime(deptReportVo1.getSTime());
              deptReportVo2.addToAllAmount(deptReportVo1.getAllAmount());
              deptReportVo2.addToAllDiscount(deptReportVo1.getAllDiscount());
              deptReportVo2.addToAllRealAmount(deptReportVo1.getAllRealAmount());
              deptReportVo2.addToAllTimes(deptReportVo1.getAllTimes());
              deptReportVo2.addToDkAmount(deptReportVo1.getDkAmount());
              deptReportVo2.addToDkTimes(deptReportVo1.getDkTimes());
              deptReportVo2.addToXjAmount(deptReportVo1.getXjAmount());
              deptReportVo2.addToBtAmount(deptReportVo1.getBtAmount());
              deptReportVo2.addToYhqAmount(deptReportVo1.getYhqAmount());
              deptReportVo2.addToXnzhTimes(deptReportVo1.getXnzhTimes());
              deptReportVo2.addToJcAmount(deptReportVo1.getJcAmount());
              deptReportVo2.addToJcTimes(deptReportVo1.getJcTimes());
            }
          }
          deptReportVo2.getDeptMealVOList().add(deptMealVO);
        }
        reList.add(deptReportVo2);

      }else{
        for (EntityXfMealInfo entityXfMealInfo:entityXfMealInfos){
          DeptReportVo.DeptMealVO deptMealVO =new DeptReportVo.DeptMealVO();
          deptMealVO.setMealNo(entityXfMealInfo.getMealNo());
          deptMealVO.setMealName(entityXfMealInfo.getMealName());
          if(deptIdList.contains(entityDeptInfo.getDeptId())){
            for (DeptReportVo deptReportVo1:objectList){
              if (!deptReportVo1.getDeptId().equals(entityDeptInfo.getDeptId())
                      || !deptReportVo1.getMealNo().equals(entityXfMealInfo.getMealNo())) continue;

              deptMealVO.setAmount(deptReportVo1.getAllAmount());
              deptMealVO.setDiscount(deptReportVo1.getAllDiscount());
              deptMealVO.setRealAmount(deptReportVo1.getAllRealAmount());
              deptMealVO.setTimes(deptReportVo1.getAllTimes());

              deptReportVo.setSTime(deptReportVo1.getSTime());
              deptReportVo.addToAllAmount(deptReportVo1.getAllAmount());
              deptReportVo.addToAllDiscount(deptReportVo1.getAllDiscount());
              deptReportVo.addToAllRealAmount(deptReportVo1.getAllRealAmount());
              deptReportVo.addToAllTimes(deptReportVo1.getAllTimes());
              deptReportVo.addToDkAmount(deptReportVo1.getDkAmount());
              deptReportVo.addToDkTimes(deptReportVo1.getDkTimes());
              deptReportVo.addToXjAmount(deptReportVo1.getXjAmount());
              deptReportVo.addToBtAmount(deptReportVo1.getBtAmount());
              deptReportVo.addToYhqAmount(deptReportVo1.getYhqAmount());
              deptReportVo.addToXnzhTimes(deptReportVo1.getXnzhTimes());
              deptReportVo.addToJcAmount(deptReportVo1.getJcAmount());
              deptReportVo.addToJcTimes(deptReportVo1.getJcTimes());
            }
          }
          deptReportVo.getDeptMealVOList().add(deptMealVO);
        }
        reList.add(deptReportVo);
      }

    }

    return ResultUtil.success(reList);
  }


  //递归操作
  //循环出有用部门树
  public List<EntityDeptInfo>  loop(List<EntityDeptInfo> list1,List<EntityDeptInfo> list2,List<Long> ins){
    int before = ins.size();
    for (EntityDeptInfo entityDeptInfo:list1){
      if(ins.contains(entityDeptInfo.getDeptId()) || ins.contains(entityDeptInfo.getParentDeptId())){
        List<Object> newList = list2.stream().map(EntityDeptInfo::getDeptId).collect(Collectors.toList());
        if(!newList.contains(entityDeptInfo.getDeptId())){
          list2.add(entityDeptInfo);
          ins.add(entityDeptInfo.getDeptId());
        }
      }
    }
    int after = ins.size();
    //无新增 返回
    if(before==after){
      return  list2;
    }else{
      return loop(list1,list2,ins);
    }
  }


  /**
   * @param getConsMerchReportsRequest
   * @return com.ocom.common.resp.Result
   * @Description:获取商户消费汇总报表
   * @author lu
   * @date 2023/3/8 14:35
   */
  @PostMapping(PayConfigUrl.Url_getConsMerchReports)
  public Result getConsMerchReports(@Validated @RequestBody GetConsMerchReportsRequest getConsMerchReportsRequest) {
    String merchOrgin = "";
    String xfMerchantName = "本单位";
    EntityXfMerchantInfo entityXfMerchantInfos = null;
    if (getConsMerchReportsRequest.getMerchId() != 0) {
      entityXfMerchantInfos = merchantInfoService.GetMerchInfo(getConsMerchReportsRequest.getComId(), getConsMerchReportsRequest.getMerchId());
      merchOrgin = merchOrgin + "," + getConsMerchReportsRequest.getMerchId() + ",";
      xfMerchantName = entityXfMerchantInfos.getMerchName();
    }
    String merchIds = String.valueOf(getConsMerchReportsRequest.getMerchId());
    List<EntityXfMerchantInfo> list = merchantInfoService.getConsMerchReports(getConsMerchReportsRequest.getComId(), merchOrgin);
    for (EntityXfMerchantInfo entityXfMerchantInfo : list) {
      merchIds = merchIds + "," + entityXfMerchantInfo.getMerchId();
    }
    if (entityXfMerchantInfos == null) {
      entityXfMerchantInfos = new EntityXfMerchantInfo();
      entityXfMerchantInfos.setMerchId(Math.toIntExact(getConsMerchReportsRequest.getMerchId()));
      entityXfMerchantInfos.setMerchName(xfMerchantName);
    }
    list.add(entityXfMerchantInfos);
    Result result = xfRecordFeign.getConsMerchReports(getConsMerchReportsRequest.getComId(), getConsMerchReportsRequest.getStartTime(), getConsMerchReportsRequest.getEndTime(), merchIds);
    if (result.getCode() != 200) {
      return result;
    }
    JSONObject dataJsonObject = JSON.parseObject(JSON.toJSONString(result.getData()), JSONObject.class);
    List<JSONObject> objectList = JSON.parseArray(JSON.toJSONString(dataJsonObject.get("list")), JSONObject.class);
    List<JSONObject> merchData = new ArrayList<>();
    for (EntityXfMerchantInfo entityXfMerchantInfo : list) {
      for (JSONObject jsonObject : objectList) {
        if (entityXfMerchantInfo.getMerchId().compareTo(jsonObject.getInteger("merchId")) == 0) {
          JSONObject jsonObjectData = new JSONObject();
          jsonObjectData.put("merchId", entityXfMerchantInfo.getMerchId());
          jsonObjectData.put("merchName", entityXfMerchantInfo.getMerchName());
          jsonObjectData.put("merchConsAmount", jsonObject.getInteger("merchConsAmount"));
          jsonObjectData.put("merchNumber", jsonObject.getInteger("merchNumber"));
          jsonObjectData.put("merchDiscount", jsonObject.getInteger("merchDiscount"));
          jsonObjectData.put("merchAmount", jsonObject.getInteger("merchAmount"));
          jsonObjectData.put("cardAmount", jsonObject.getInteger("cardAmount"));
          jsonObjectData.put("cardNumber", jsonObject.getInteger("cardNumber"));
          jsonObjectData.put("timesAmount", jsonObject.getInteger("timesAmount"));
          jsonObjectData.put("timesNumber", jsonObject.getInteger("timesNumber"));
          jsonObjectData.put("days", jsonObject.getInteger("days"));
          merchData.add(jsonObjectData);
        }
      }
    }
    Map<String, Object> map = new HashMap<>();
    map.put("channelData", new ArrayList<>());
    map.put("groupData", new ArrayList<>());
    map.put("merchData", merchData);

    EntityXfMerchPayInfo entityXfMerchPayInfo = xfMerchPayInfoService.getPayInfo(getConsMerchReportsRequest.getComId(), getConsMerchReportsRequest.getMerchId().intValue());
    if (entityXfMerchPayInfo == null) {
      return ResultUtil.success(map);
    }


    Result result1 = xfRecordFeign.getChannelData(getConsMerchReportsRequest.getComId(),
        entityXfMerchPayInfo.getCompanyId(),
        getConsMerchReportsRequest.getStartTime(),
        getConsMerchReportsRequest.getEndTime());


    Map<Integer, String> payWays = new HashMap<>();
    List<Integer> payWayList = new ArrayList<>();
    List<ChannelDataVo> channelDataVos = new ArrayList<>();
    if (result1.getCode() == 200 && result1.getData() != null) {
      channelDataVos = JSON.parseArray(JSON.toJSONString(result1.getData()), ChannelDataVo.class);
      if (channelDataVos != null && channelDataVos.size() > 0) {

        payWayList = channelDataVos.stream().map(ChannelDataVo -> ChannelDataVo.getChannelPayway()).collect(Collectors.toList());

        List<EntityPayChannel> payChannels = payChannelService.payList();
        payWays = payChannels.stream().collect(Collectors.toMap(e -> e.getPayWay(),
            e -> e.getName(),
            (e1, e2) -> e1));
        for (int i = 0; i < channelDataVos.size(); i++) {
          ChannelDataVo channelDataVo = channelDataVos.get(i);
          if (channelDataVo.getChannelPayway() == 0) {
            channelDataVos.remove(i);
            continue;
          }
        }

        for (int i = 0; i < channelDataVos.size(); i++) {
          ChannelDataVo channelDataVo = channelDataVos.get(i);
          if (payWays.containsKey(channelDataVo.getChannelPayway())) {
            channelDataVo.setChannelName(xfMerchantName + ":" + payWays.get(channelDataVo.getChannelPayway()));
          } else {
            channelDataVo.setChannelName(xfMerchantName + ":其他(" + channelDataVo.getChannelPayway() + ")");
          }
          channelDataVos.set(i, channelDataVo);
        }

      }
    }

    ChannelDataVo channelDataVo = new ChannelDataVo();
    channelDataVo.setChannelPayway(0);
    channelDataVo.setChannelName("未知");
    channelDataVo.setChannelPayway(0);
    channelDataVos.add(channelDataVo);
    map.put("channelData", channelDataVos);

    if (payWayList.size() > 0) {
      GetGroupDataRequest request = new GetGroupDataRequest();
      request.setComId(getConsMerchReportsRequest.getComId());
      request.setPayChannelNo(entityXfMerchPayInfo.getCompanyId());
      request.setMerchId(getConsMerchReportsRequest.getMerchId().intValue());
      request.setStartTime(getConsMerchReportsRequest.getStartTime());
      request.setEndTime(getConsMerchReportsRequest.getEndTime());
      request.setPayWay(payWayList);
      Result result2 = xfRecordFeign.getGroupData(request);
      map.put("groupData", result2.getData());
    }

    return ResultUtil.success(map);
  }

  @PostMapping(PayConfigUrl.Url_getPointMealPreReports)
  public Result getPointMealPreReports(@Validated @RequestBody GetPointMealPreReportsRequest request) {
    HashMap<String, Object> map = new HashMap<>();
    Result pointMealPre = xfRecordFeign.getPointMealPre(request);
    List<EntityXfMealInfo> mealInfos = mealInfoService.GetMealNameInfo(null, request.getComId(), null, null);
    map.put("list", pointMealPre.getData());
    map.put("meal", mealInfos);
    return ResultUtil.success(map);
  }

  @PostMapping(PayConfigUrl.Url_getPointMealSendReports)
  public Result getPointMealSendReports(@Validated @RequestBody GetPointMealSendReportsRequest request) {
    HashMap<String, Object> map = new HashMap<>();
    Result pointMealSend = xfRecordFeign.getPointMealSend(request);
    List<EntityXfMealInfo> mealInfos = mealInfoService.GetMealNameInfo(null, request.getComId(), null, null);
    map.put("list", pointMealSend.getData());
    map.put("meal", mealInfos);
    return ResultUtil.success(map);
  }

  @PostMapping(PayConfigUrl.Url_getPointMealSendReportsXM)
  public Result getPointMealSendReportsXM(@Validated @RequestBody GetPointMealSendReportsXMRequest request) {

//        GetOrderPlanDishesRequest orderPlanDishesRequest = new GetOrderPlanDishesRequest();
//        orderPlanDishesRequest.setComId(request.getComId());
//        orderPlanDishesRequest.setMealDate(request.getMealDate());
//        orderPlanDishesRequest.setMealNo(request.getMealNo());
//        orderPlanDishesRequest.setPointId(request.getPointId());
//        orderPlanDishesRequest.setReceiptId(request.getReceiptId());
//
//        Result orderPlanDishes = mealOrderController.getOrderPlanDishes(orderPlanDishesRequest);
//
//        if (200 != orderPlanDishes.getCode() || null == orderPlanDishes.getData()) {
//            return ResultUtil.error(ResultEnum.Err_4600);
//        }
//
//        List<GetOrderPlanDishesResponse> responseList = JSON.parseArray(JSON.toJSONString(orderPlanDishes.getData()), GetOrderPlanDishesResponse.class);
//
//        if (0 == responseList.size()) {
//            return ResultUtil.error(ResultEnum.Err_4600);
//        }
//
//        request.setDishesList(responseList);
    Result mealSendReportsXMByGoods = xfRecordFeign.getMealSendReportsXMByGoods(request);
    if (200 != mealSendReportsXMByGoods.getCode()) {
      return ResultUtil.error(ResultEnum.Err_4600);
    }

    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(mealSendReportsXMByGoods.getData()));

    List<EntityXfGoodListDishes> mealSendReports = JSON.parseArray(JSON.toJSONString(jsonObject.get("list")), EntityXfGoodListDishes.class);

    GetAdReceiptInfoRequest getAdReceiptInfoRequest = new GetAdReceiptInfoRequest();
    getAdReceiptInfoRequest.setComId(request.getComId());
    List<EntityReceiptAddress> adReceiptInfo = receiptAddressService.getAdReceiptInfo(request.getComId(), getAdReceiptInfoRequest);
    Map<Integer, EntityReceiptAddress> receiptMap = adReceiptInfo.stream().collect(Collectors.toMap(EntityReceiptAddress::getReceiptId, EntityReceiptAddress -> EntityReceiptAddress));

    List<EntityXfGoodListDishes> collect = mealSendReports.stream().map(e -> {
      EntityReceiptAddress entityReceiptAddress = receiptMap.get(e.getReceiptId());
      if (null != entityReceiptAddress) {
        e.setReceiptName(entityReceiptAddress.getReceiptName());
        e.setRemark(entityReceiptAddress.getRemark());
      }
      return e;
    }).collect(Collectors.toList());

    Map<String, Object> map = new HashMap<>();
    map.put("dishesList", jsonObject.get("dishes"));
    map.put("list", collect);
    return ResultUtil.success(map);
  }

  @PostMapping(PayConfigUrl.Url_getConsumeDetailError)
  public Result getConsumeDetailError(@RequestBody ConsumeDetailErrorRequest request) {
    //消费明细错误
    return xfRecordProcessService.selectConsumeDetailError(Long.valueOf(request.getComId()), request);
  }
}
